import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
//创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 60000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

//请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 是否需要设置 token
    const isToken = (config.headers || {})?.isToken === false;
    let token = sessionStorage.getItem("token");
    if (isToken && token) {
        config.headers.Authorization = "Bearer "+token
    }
    
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status, message } = response.data;
    // 二进制数据则直接返回
    if (
      response.request.responseType === "blob" ||
      response.request.responseType === "arraybuffer"
    ) {
      return response;
    }
    if(status === 200) {
        return response.data;
    } else if(status === 401) {
      ElMessage.error(message || "token 已过期");
      // return Promise.reject(response.data);
    }
    ElMessage.error(message || "系统出错");
    return Promise.reject(new Error(message || "Error"));
  },
  (error: any) => {
    if (error.response?.data?.data) {
        const { message } = error.response.data.data;
        if(Array.isArray(message)) {
            ElMessage.error(message.join(";") || "系统出错");
        } else {
          ElMessage.error(message || "系统出错");
        }
    }
    return Promise.reject(new Error(error.message || "Error"));
  }
);

// 导出 axios 实例
export default service;
